import type { MobileLoginRequest, MobileSmsLoginResponse } from '@/api/modules/user/user.type.ts'
import userService from '@/api/modules/user/user.ts'
import { getToken, removeToken, setToken } from '@/utils/auth.ts'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface UserInfo {
  /**
   * 充值余额
   */
  balanceNumber?: number
  /**
   * 客户姓名
   */
  customerName?: string
  /**
   * 客户电话
   */
  customerPhone?: string
  /**
   * 客户类型-字典（dictType：custom_type）
   */
  customerType?: string
  /**
   * 客户类型-翻译后值
   */
  customerTypeDict?: string
  /**
   * 客户主表主键UUID
   */
  customerUuid?: string
  /**
   * 客户微信号
   */
  customerWechat?: string
  /**
   * 赠送金额
   */
  giftMoney?: number
  /**
   * 客户id
   */
  id?: number
  /**
   * 上级代理名称
   */
  parentCustomerName?: string
  /**
   * 上级代理uuid
   */
  parentCustomerUuid?: string
  /**
   * 注册时间
   */
  registerDatetime?: Date
  /**
   * 备注
   */
  remark?: string
  /**
   * 奖励开闭标志（1：打开 0：关闭）-字典（dictType：reward_flag）
   */
  rewardFlag?: number
  /**
   * 奖励开闭标志
   */
  rewardFlagDict?: string
  /**
   * 分享编号
   */
  shareCode?: string
  /**
   * 签名图片
   */
  signFileUrl?: string
  /**
   * 首次充值
   */

}

const useUserStore = defineStore('user', () => {
  const token = ref<string>(getToken() || '')
  const storedUserInfo = uni.getStorageSync('userInfo')
  const userInfo = ref<UserInfo | null>(
    storedUserInfo && typeof storedUserInfo === 'object' ? storedUserInfo : null,
  )
  const reportUnreadNumber = ref<number>(0)

  const totalRechargeAmount = ref<number>(0)
  const bonusAmount = ref<number>(0)

  async function handleLoginSuccess(tokenStr: string) {
    setToken(tokenStr)
    token.value = tokenStr
    await getUserInfo()
  }

  async function mobileLogin(loginInfo: MobileLoginRequest): Promise<boolean> {
    try {
      const res = await userService.mobileLogin(loginInfo)
      if (res?.code === 200 && res.token) {
        await handleLoginSuccess(res.token)
        return true
      }
    }
    catch (err) {
      console.error('登录失败:', err)
    }
    return false
  }

  async function mobileSmsLogin(smsInfo: MobileSmsLoginResponse): Promise<any> {
    try {
      const res = await userService.mobileSmsLogin(smsInfo)
      if (res?.code === 200 && res.token) {
        await handleLoginSuccess(res.token)
        return res
      }
    }
    catch (err) {
      console.error('mobileSmsLogin error:', err)
      return err
    }
  }

  async function getUserInfo(): Promise<void> {
    try {
      const res = await userService.getInfo()
      if (res?.code === 200 && res.data) {
        userInfo.value = res.data
        totalRechargeAmount.value = res.data.balanceNumber + res.data.giftMoney
        bonusAmount.value = res.data.giftMoney
        uni.setStorageSync('userInfo', res.data)
      }
    }
    catch (err) {
      logout()
      console.error('getUserInfo error:', err)
      uni.showToast({ title: '获取用户信息失败', icon: 'none' })
    }
  }

  function logout() {
    token.value = ''
    userInfo.value = null
    totalRechargeAmount.value = 0
    bonusAmount.value = 0
    reportUnreadNumber.value = 0
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('token')
    removeToken()
  }

  async function fetchUnreadReportNumber() {
    try {
      const res = await userService.getInfo()
      if (res?.code === 200 && typeof res.data?.reportUnreadNumber === 'number') {
        reportUnreadNumber.value = res.data.reportUnreadNumber
      }
      console.log('获取未读数量成功:', reportUnreadNumber.value)
    }
    catch (err) {
      reportUnreadNumber.value = 0
      console.error('获取未读数量失败:', err)
    }
  }

  // 刷新用户信息并检查余额是否足够
  async function refreshAndCheckBalance(requiredAmount: number): Promise<boolean> {
    await getUserInfo()
    return (totalRechargeAmount.value ?? 0) >= requiredAmount
  }
  return {
    token,
    userInfo,
    reportUnreadNumber,
    totalRechargeAmount,
    bonusAmount,
    mobileLogin,
    mobileSmsLogin,
    getUserInfo,
    logout,
    fetchUnreadReportNumber,
    refreshAndCheckBalance,
  }
})

export default useUserStore
